home *** CD-ROM | disk | FTP | other *** search
/ The Atari Compendium / The Atari Compendium (Toad Computers) (1994).iso / files / prgtools / mint / shells / bashsrc.zoo / jobs.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-06-05  |  39.8 KB  |  1,722 lines

  1. /* The thing that makes children, remembers them, and contains wait loops. */
  2.  
  3. /* Copyright (C) 1989 Free Software Foundation, Inc.
  4.  
  5. This file is part of GNU Bash, the Bourne Again SHell.
  6.  
  7. Bash is free software; you can redistribute it and/or modify it under
  8. the terms of the GNU General Public License as published by the Free
  9. Software Foundation; either version 1, or (at your option) any later
  10. version.
  11.  
  12. Bash is distributed in the hope that it will be useful, but WITHOUT ANY
  13. WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14. FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15. for more details.
  16.  
  17. You should have received a copy of the GNU General Public License along
  18. with Bash; see the file COPYING.  If not, write to the Free Software
  19. Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
  20.  
  21. /* Something that can be ignored. */
  22. #define IGNORE_ARG (char *)0
  23.  
  24. #include "config.h"
  25.  
  26. #ifndef JOB_CONTROL
  27. #include "nojobs.c"
  28. #else
  29.  
  30. #include <stdio.h>
  31. #include <signal.h>
  32. #include <errno.h>
  33. #include <sys/types.h>
  34.  
  35. #include <sys/time.h>
  36. #include <sys/resource.h>
  37. #include <sys/file.h>
  38.  
  39. #include <fcntl.h>
  40. #include <sys/ioctl.h>
  41. #include <sys/param.h>
  42.  
  43. /* Terminal handling stuff, to save and restore tty state. */
  44. #define NEW_TTY_DRIVER
  45.  
  46. #if defined(SYSV) || defined(hpux) || defined(ALTOS)
  47. #undef NEW_TTY_DRIVER
  48. #endif /* SYSV || hpux || ALTOS */
  49.  
  50. #ifdef NEW_TTY_DRIVER
  51. #include <sgtty.h>
  52. #else
  53. #include <termio.h>
  54. #endif /* NEW_TTY_DRIVER */
  55.  
  56. /* For the TIOCGPGRP and TIOCSPGRP ioctl parameters on HP-UX */
  57.  
  58. #ifdef hpux
  59. #include <bsdtty.h>
  60. #endif /* hpux */
  61.  
  62. #include "shell.h"
  63. #include "jobs.h"
  64.  
  65. /* Not all systems define errno in errno.h. */
  66. extern int errno;
  67.  
  68. #ifndef sigmask
  69. #define sigmask(x) (1 << ((x)-1))
  70. #endif
  71.  
  72. #ifndef SIGABRT
  73. #define SIGABRT SIGIOT
  74. #endif
  75.  
  76. #ifndef SIGCHLD
  77. #define SIGCHLD SIGCLD
  78. #endif
  79.  
  80. /* The array of known jobs. */
  81. JOB **jobs = (JOB **)NULL;
  82.  
  83. /* The number of slots currently allocated to JOBS. */
  84. int job_slots = 0;
  85.  
  86. /* The number of additional slots to allocate when we run out. */
  87. #define JOB_SLOTS 5
  88.  
  89. /* The controlling tty for this shell. */
  90. int shell_tty;
  91.  
  92. /* The shell's process group. */
  93. int shell_pgrp = -1;
  94.  
  95. /* The terminal's process group. */
  96. int terminal_pgrp = -1;
  97.  
  98. /* The process group of the shell's parent. */
  99. int original_pgrp = -1;
  100.  
  101. /* The process group of the pipeline currently being made. */
  102. int pipeline_pgrp = 0;
  103.  
  104. /* The job which is current; i.e. the one that `%+' stands for. */
  105. int current_job = NO_JOB;
  106.  
  107. /* The previous job; i.e. the one that `%-' stands for. */
  108. int previous_job = NO_JOB;
  109.  
  110. /* Last child made by the shell.  */
  111. int last_made_pid = -1;
  112.  
  113. /* Pid of the last asynchronous child. */
  114. int last_asynchronous_pid = -1;
  115.  
  116. /* Non-zero allows asynchronous job notification.  If not set,
  117.    then job state notification only takes place just before a
  118.    prompt is printed. */
  119. int asynchronous_notification = 0;
  120.  
  121. #ifndef hpux
  122. /* The total amount of system time spent running processes for me. */
  123. struct timeval total_systime = {0, 0};
  124. long system_minutes_used = 0;
  125. int system_seconds_used = 0;
  126.  
  127. /* The total amount of user time spent running processes for me. */
  128. struct timeval total_usertime = {0, 0};
  129. long user_minutes_used = 0;
  130. int user_seconds_used = 0;
  131. #endif /* hpux */
  132.  
  133. /* The pipeline currently being built. */
  134. PROCESS *the_pipeline = (PROCESS *)NULL;
  135.  
  136. /* If this is non-zero, do job control. */
  137. int job_control = 1;
  138.  
  139. /* Call this when you start making children. */
  140. int already_making_children = 0;
  141.  
  142. /* These are definitions to map POSIX 1003.1 functions onto existing BSD
  143.    library functions and system calls. */
  144.  
  145. #define setpgid(pid, pgrp)    setpgrp (pid, pgrp)
  146. #define tcsetpgrp(fd, pgrp)    ioctl ((fd), TIOCSPGRP, &(pgrp))
  147.  
  148. tcgetpgrp (fd)
  149.      int fd;
  150. {
  151.   int pgrp;
  152.  
  153.   /* ioctl will handle setting errno correctly. */
  154.   if (ioctl (fd, TIOCGPGRP, &pgrp) < 0)
  155.     return (-1);
  156.   return (pgrp);
  157. }
  158.  
  159. /* END of POISX 1003.1 definitions. */
  160.  
  161. making_children ()
  162. {
  163.   if (already_making_children)
  164.     return;
  165.  
  166.   already_making_children = 1;
  167.   start_pipeline ();
  168. }
  169.  
  170. stop_making_children ()
  171. {
  172.   already_making_children = 0;
  173. }
  174.  
  175. /* Start building a pipeline.  */
  176. start_pipeline ()
  177. {
  178.   if (the_pipeline)
  179.     {
  180.       discard_pipeline (the_pipeline);
  181.       the_pipeline = (PROCESS *)NULL;
  182.       pipeline_pgrp = 0;
  183.     }
  184. }
  185.  
  186. /* Stop building a pipeline.  Install the process list in the job array.
  187.    This returns the index of the newly installed job.
  188.    DEFERRED is a command structure to be executed upon satisfactory
  189.    execution exit of this pipeline. */
  190. int
  191. stop_pipeline (async, deferred)
  192.      int async;
  193.      COMMAND *deferred;
  194. {
  195.   register int i, j;
  196.   int oldmask;
  197.   JOB *newjob = (JOB *)NULL;
  198.   char *get_string_value ();
  199.  
  200.   oldmask = sigblock (sigmask (SIGCHLD));
  201.  
  202.   cleanup_dead_jobs ();
  203.  
  204.   if (!job_slots)
  205.     {
  206.       jobs =
  207.     (JOB **)xmalloc ((1 + (job_slots = JOB_SLOTS)) * sizeof (JOB *));
  208.  
  209.       /* Now blank out these new entries. */
  210.       for (i = 0; i < job_slots; i++)
  211.     jobs[i] = (JOB *)NULL;
  212.     }
  213.  
  214.   /* Scan from the last slot backward, looking for the next free one. */
  215.   for (i = job_slots; i; i--)
  216.     if (jobs[i - 1])
  217.       break;
  218.  
  219.   /* Do we need more room? */
  220.   if (i == job_slots)
  221.     {
  222.       jobs = (JOB **)realloc
  223.     (jobs, (1 + (job_slots += JOB_SLOTS)) * sizeof (JOB *));
  224.  
  225.       for (j = i; j < job_slots; j++)
  226.     jobs[j] = (JOB *)NULL;
  227.     }
  228.  
  229.   /* Add the current pipeline to the job list. */
  230.   if (the_pipeline)
  231.     {
  232.       extern int errno, sys_nerr;
  233.       extern char *sys_errlist[];
  234.       register PROCESS *p;
  235.  
  236.       newjob = (JOB *)xmalloc (sizeof (JOB));
  237.  
  238.       for (p = the_pipeline; p->next != the_pipeline; p = p->next);
  239.       p->next = (PROCESS *)NULL;
  240.       newjob->pipe = (PROCESS *)reverse_list (the_pipeline);
  241.       for (p = newjob->pipe; p->next; p = p->next);
  242.       p->next = newjob->pipe;
  243.  
  244.       the_pipeline = (PROCESS *)NULL;
  245.       newjob->pgrp = pipeline_pgrp;
  246.       pipeline_pgrp = 0;
  247.  
  248.       /* Flag to see if in another pgrp. */
  249.       newjob->job_control = job_control;
  250.  
  251.       /* Set the state of this pipeline. */
  252.       {
  253.     register PROCESS *p = newjob->pipe;
  254.     register int any_alive = 0;
  255.     register int any_stopped = 0;
  256.  
  257.     do
  258.       {
  259.         any_alive |= p->running;
  260.         any_stopped |= WIFSTOPPED (p->status);
  261.         p = p->next;
  262.       }
  263.     while (p != newjob->pipe);
  264.  
  265.     if (any_alive)
  266.       {
  267.         newjob->state = JRUNNING;
  268.       }
  269.     else
  270.       {
  271.         if (any_stopped)
  272.           newjob->state = JSTOPPED;
  273.         else
  274.           newjob->state = JDEAD;
  275.       }
  276.       }
  277.  
  278.       newjob->notified = 0;
  279.  
  280.       newjob->wd = get_string_value ("PWD");
  281.  
  282.       if (newjob->wd)
  283.     newjob->wd = savestring (newjob->wd);
  284.       else
  285.     newjob->wd = (char *)get_working_directory ("");
  286.  
  287.       if (!(newjob->wd))
  288.     newjob->wd = savestring ("<no directory>");
  289.  
  290.       newjob->deferred = deferred;
  291.  
  292.       jobs[i] = newjob;
  293.     }
  294.  
  295.   if (async)
  296.     {
  297.       if (newjob)
  298.     newjob->foreground = 0;
  299.       reset_current ();
  300.     }
  301.   else
  302.     {
  303.       if (newjob)
  304.     {
  305.       newjob->foreground = 1;
  306.       /*
  307.        *            !!!!! NOTE !!!!!  (chet@ins.cwru.edu)
  308.        *
  309.        * The currently-accepted job control wisdom says to set the
  310.        * terminal's process group n+1 times in an n-step pipeline:
  311.        * once in the parent and once in each child.  This is where
  312.        * the parent gives it away.
  313.        *
  314.        */
  315.       if (job_control && pipeline_pgrp)
  316.         give_terminal_to (pipeline_pgrp);
  317.     }
  318.     }
  319.  
  320.   stop_making_children ();
  321.   sigsetmask (oldmask);
  322.   return (current_job);
  323. }
  324.  
  325. /* Delete all DEAD jobs that the user had received notification about. */
  326. cleanup_dead_jobs ()
  327. {
  328.   int oldmask = sigblock (sigmask (SIGCHLD));
  329.   register int i;
  330.  
  331.   for (i = 0; i < job_slots; i++)
  332.     if (jobs[i] && JOBSTATE (i) == JDEAD && jobs[i]->notified)
  333.       delete_job (i);
  334.  
  335.   sigsetmask (oldmask);
  336. }
  337.  
  338. /* Delete the job at INDEX from the job list. */
  339. delete_job (index)
  340.      int index;
  341. {
  342.   register JOB *temp = jobs[index];
  343.  
  344.   if (index == current_job || index == previous_job)
  345.     reset_current ();
  346.  
  347.   jobs[index] = (JOB *)NULL;
  348.  
  349.   free (temp->wd);
  350.   discard_pipeline (temp->pipe);
  351.  
  352.   if (temp->deferred)
  353.     dispose_command (temp->deferred);
  354.  
  355.   free (temp);
  356. }
  357.  
  358. /* Get rid of the data structure associated with a process chain. */
  359. discard_pipeline (chain)
  360.      register PROCESS *chain;
  361. {
  362.   register PROCESS *this, *next;
  363.  
  364.   this = chain;
  365.   do
  366.     {
  367.       next = this->next;
  368.       if (this->command)
  369.     free (this->command);
  370.       free (this);
  371.       this = next;
  372.     }
  373.   while (this != chain);
  374. }
  375.  
  376. /* Add this process to the chain being built in the_pipeline.
  377.    NAME is the command string that will be exec'ed later.
  378.    PID is the process id of the child. */
  379. add_process (name, pid)
  380.      char *name;
  381.      int pid;
  382. {
  383.   PROCESS *t = (PROCESS *)xmalloc (sizeof (PROCESS));
  384.  
  385.   t->next = the_pipeline;
  386.   t->pid = pid;
  387.   t->status.w_status = 0;
  388.   t->running = 1;
  389.   t->command = name;
  390.   the_pipeline = t;
  391.  
  392.   if (!(t->next))
  393.     {
  394.       t->next = t;
  395.     }
  396.   else
  397.     {
  398.       register PROCESS *p = t->next;
  399.  
  400.       while (p->next != t->next) p = p->next;
  401.       p->next = t;
  402.     }
  403. }
  404.  
  405. /* Map FUNC over the list of jobs.  If FUNC returns non-zero,
  406.    then it is time to stop mapping, and that is the return value
  407.    for map_over_jobs.  FUNC is called with a JOB, arg1, arg2,
  408.    and INDEX. */
  409. map_over_jobs (func, arg1, arg2)
  410.      Function *func;
  411. {
  412.   register int i;
  413.  
  414.   for (i = 0; i < job_slots; i++)
  415.     {
  416.       if (jobs[i])
  417.     {
  418.       int result = (*func)(jobs[i], arg1, arg2, i);
  419.       if (result)
  420.         return (result);
  421.     }
  422.     }
  423.   return (0);
  424. }
  425.  
  426. /* Return the pipeline that PID belongs to.  Note that the pipeline
  427.    doesn't have to belong to a job. */
  428. PROCESS *
  429. find_pipeline (pid)
  430.      int pid;
  431. {
  432.   int job;
  433.  
  434.   /* See if this process is in the pipeline that we are building. */
  435.   if (the_pipeline)
  436.     {
  437.       register PROCESS *p = the_pipeline;
  438.  
  439.       do
  440.     {
  441.       /* Return it if we found it. */
  442.       if (p->pid == pid)
  443.         return (p);
  444.  
  445.       p = p->next;
  446.     }
  447.       while (p != the_pipeline);
  448.     }
  449.  
  450.   job = find_job (pid);
  451.  
  452.   if (job == NO_JOB)
  453.     return ((PROCESS *)NULL);
  454.   else
  455.     return (jobs[job]->pipe);
  456. }
  457.  
  458. /* Return the job index that PID belongs to, or NO_JOB if it doesn't
  459.    belong to any job. */
  460. int
  461. find_job (pid)
  462.      int pid;
  463. {
  464.   register int i;
  465.   register PROCESS *p;
  466.  
  467.   for (i = 0; i < job_slots; i++)
  468.     {
  469.       if (jobs[i])
  470.     {
  471.       p = jobs[i]->pipe;
  472.  
  473.       do
  474.         {
  475.           if (p->pid == pid)
  476.         return (i);
  477.  
  478.           p = p->next;
  479.         }
  480.       while (p != jobs[i]->pipe);
  481.     }
  482.     }
  483.  
  484.   return (NO_JOB);
  485. }
  486.  
  487. /* Print descriptive information about the job with leader pid PID. */
  488. describe_pid (pid)
  489.      int pid;
  490. {
  491.   int job;
  492.   int oldmask = sigblock (sigmask (SIGCHLD));
  493.  
  494.   job = find_job (pid);
  495.  
  496.   if (job != NO_JOB)
  497.     printf ("[%d] %d\n", job + 1, pid);
  498.   else
  499.     programming_error ("describe_pid: No such pid (%d)!\n", pid);
  500.  
  501.   sigsetmask (oldmask);
  502. }
  503.  
  504.  
  505. /* This is the way to print out information on a job if you
  506.    know the index.  FORMAT is:
  507.  
  508.     0)   [1]+ Running        emacs
  509.     1)   [1]+ 2378 Running    emacs
  510.    -1)   [1]+ 2378        emacs
  511.  
  512.     0)   [1]+ Stopped        ls | more
  513.     1)   [1]+ 2369 Stopped    ls
  514.           2367          | more
  515.  */
  516. pretty_print_job (index, format, stream)
  517.      int index, format;
  518.      FILE *stream;
  519. {
  520.   register PROCESS *p;
  521.   int first, oldmask;
  522.   union wait first_job_cond;
  523.   int name_padding;
  524.  
  525.   oldmask = sigblock (sigmask (SIGCHLD));
  526.  
  527.   fprintf (stream, "[%d]%c ", index + 1,
  528.        (index == current_job) ? '+':
  529.        (index == previous_job) ? '-' : ' ');
  530.   
  531.   first = 1;
  532.   p = jobs[index]->pipe;
  533.  
  534.   do
  535.     {
  536.       if (!first && !format)
  537.     fprintf (stream, " |");
  538.       else if (!first)
  539.     fprintf (stream, "     ");
  540.  
  541.       if (format)
  542.     fprintf (stream, "%d", p->pid);
  543.  
  544.       fprintf (stream, " ");
  545.  
  546.       if (format > -1)
  547.     {
  548.       extern char *sys_siglist[];
  549.       union wait status;
  550.       char *temp = "Done";
  551.  
  552.       if (JOBSTATE (index) == JSTOPPED && !format)
  553.         temp = "Stopped";
  554.  
  555.       status = p->status;
  556.       if (p->running)
  557.         {
  558.           temp = "Running";
  559.         }
  560.       else
  561.         {
  562.           if (status.w_termsig)
  563.         if (status.w_termsig == WSTOPPED)
  564.           temp = sys_siglist[status.w_stopsig];
  565.         else
  566.           temp = sys_siglist[status.w_termsig];
  567.         }
  568.  
  569.       if (first)
  570.         first_job_cond = status;
  571.       else
  572.         if (format)
  573.           {
  574.         if (status.w_status == first_job_cond.w_status)
  575.           temp = "";
  576.           }
  577.         else
  578.           temp = (char *)NULL;
  579.  
  580.       if (temp)
  581.         {
  582.           fprintf (stream, "%s", temp);
  583.  
  584.           if (strlen (temp))
  585.         name_padding = LONGEST_SIGNAL_DESC - strlen (temp);
  586.           else
  587.         name_padding = LONGEST_SIGNAL_DESC - 2; /* strlen ("| ") */
  588.  
  589.           fprintf (stream, "%*s", name_padding, "");
  590.  
  591.           if ((status.w_termsig != WSTOPPED) && (status.w_coredump))
  592.         fprintf (stream, "(core dumped) ");
  593.         }
  594.     }
  595.  
  596.       if (first)
  597.     {
  598.       /* fprintf (stream, "  "); */
  599.     }
  600.       else
  601.     {
  602.       if (format)
  603.         fprintf (stream, "| ");
  604.     }
  605.  
  606.       fprintf (stream, "%s", p->command);
  607.  
  608.       if (p->next == jobs[index]->pipe) 
  609.     {
  610.       if (JOBSTATE (index) == JRUNNING && jobs[index]->foreground == 0)
  611.         fprintf (stream, " &");
  612.  
  613.       if (strcmp (get_string_value ("PWD"), jobs[index]->wd) != 0)
  614.         fprintf (stream,
  615.              "  (wd: %s)", polite_directory_format (jobs[index]->wd));
  616.     }
  617.  
  618.       if (format || (p->next == jobs[index]->pipe))
  619.     fprintf (stream, "\r\n");
  620.       
  621.       first = 0;
  622.       p = p->next;
  623.     } while (p != jobs[index]->pipe);
  624.   fflush (stream);
  625.   sigsetmask (oldmask);
  626. }
  627.  
  628. list_one_job (job, format, ignore, index)
  629.      JOB *job;
  630.      int format, ignore, index;
  631. {
  632.   pretty_print_job (index, format, stdout);
  633.   return (0);
  634. }
  635.  
  636. /* List jobs.  If FORMAT is non-zero, then the long form of the information
  637.    is printed, else just a short version. */
  638. list_jobs (format)
  639.      int format;
  640. {
  641.   cleanup_dead_jobs ();
  642.   map_over_jobs (list_one_job, format, (int) IGNORE_ARG);
  643. }
  644.  
  645. /* Fork, handling errors.  Returns the pid of the newly made child, or 0.
  646.    COMMAND is just for remembering the name of the command; we don't do
  647.    anything else with it.  ASYNC_P says what to do with the tty.  If
  648.    non-zero, then don't give it away. */
  649. int
  650. make_child (command, async_p)
  651.      char *command;
  652.      int async_p;
  653. {
  654.   int pid, oldmask;
  655.   
  656.   oldmask = sigblock (sigmask (SIGINT) | sigmask (SIGCHLD));
  657.  
  658.   making_children ();
  659.  
  660.   /* Make new environment array if neccessary. */
  661.   maybe_make_export_env ();
  662.  
  663.   /* Create the child, handle severe errors. */
  664.   if ((pid = fork ()) < 0)
  665.     {
  666.       extern sighandler throw_to_top_level ();
  667.  
  668.       sigsetmask (oldmask);
  669.       report_error ("Memory exhausted or process overflow!");
  670.       throw_to_top_level ();
  671.     }
  672.  
  673.   if (!pid)
  674.     {
  675.       /* In the child.  Give this child the right process group, set the
  676.      signals to the default state for a new process. */
  677.       signal (SIGINT, SIG_DFL);
  678.       signal (SIGQUIT, SIG_DFL);
  679.       signal (SIGTERM, SIG_DFL);
  680.  
  681.       /* Set the resource limits for this child. (In ulimit.c). */
  682.       set_process_resource_limits ();
  683.  
  684.       /* Restore the sigmask before changing the tty pgrp, since a
  685.      SIGINT may have occurred in fork (), and we don't want to
  686.      surprise read (). */
  687. /*      sigsetmask (oldmask); */
  688.  
  689.       if (job_control)
  690.     {
  691.       /* All processes in this pipeline belong in the same
  692.          process group. */
  693.  
  694.       if (!pipeline_pgrp)    /* Then this is the first child. */
  695.         pipeline_pgrp = getpid ();
  696.  
  697.       /* Check for running command in backquotes. */
  698.       if (pipeline_pgrp == shell_pgrp)
  699.         {
  700.           signal (SIGTSTP, SIG_IGN);
  701.           signal (SIGTTOU, SIG_IGN);
  702.           signal (SIGTTIN, SIG_IGN);
  703.         }
  704.       else
  705.         {
  706.           signal (SIGTSTP, SIG_DFL);
  707.           signal (SIGTTOU, SIG_DFL);
  708.           signal (SIGTTIN, SIG_DFL);
  709.         }
  710.     
  711.       if (!async_p)
  712.         give_terminal_to (pipeline_pgrp);
  713.  
  714.       setpgrp (0, pipeline_pgrp);
  715.     }
  716.       else            /* Without job control... */
  717.     {
  718.       if (!pipeline_pgrp)
  719.         pipeline_pgrp = shell_pgrp;
  720.  
  721.       signal (SIGTSTP, SIG_IGN);
  722.       signal (SIGTTOU, SIG_IGN);
  723.       signal (SIGTTIN, SIG_IGN);
  724.  
  725.       if (async_p)
  726.         {
  727.           signal (SIGINT, SIG_IGN);
  728.           signal (SIGQUIT, SIG_IGN);
  729.         }
  730.     }
  731.  
  732.       if (async_p)
  733.     last_asynchronous_pid = getpid ();
  734.     }
  735.   else
  736.     {
  737.       /* In the parent.  Remember the pid of the child just created
  738.      as the proper pgrp if this is the first child. */
  739.  
  740.       if (job_control)
  741.     {
  742.       if (!pipeline_pgrp)
  743.         {
  744.           pipeline_pgrp = pid;
  745.           /* Don't twiddle terminal pgrps in the parent!  This is the bug,
  746.          not the good thing of twiddling them in the child! */
  747.           /* give_terminal_to (pipeline_pgrp); */
  748.         }
  749.       setpgid (pid, pipeline_pgrp);
  750.     }
  751.       else
  752.     {
  753.       if (!pipeline_pgrp)
  754.         pipeline_pgrp = shell_pgrp;
  755.     }
  756.  
  757.       /* Place all processes into the jobs array regardless of the
  758.      state of job_control.  */
  759.       add_process (command, pid);
  760.  
  761.       if (async_p)
  762.     last_asynchronous_pid = pid;
  763.  
  764.       last_made_pid = pid;
  765.     }
  766.   sigsetmask (oldmask);
  767.   return (pid);
  768. }
  769.  
  770. /* When we end a job abnormally, or if we stop a job, we set the tty to the
  771.    state kept in here.  When a job ends normally, we set the state in here
  772.    to the state of the tty. */
  773.  
  774. #ifdef NEW_TTY_DRIVER
  775. static struct sgttyb shell_tty_info;
  776. static struct tchars shell_tchars;
  777. static struct ltchars shell_ltchars;
  778. #else
  779. static struct termio shell_tty_info;
  780. #endif
  781.  
  782. /* Fill the contents of shell_tty_info with the current tty info. */
  783. get_tty_state ()
  784. {
  785.   int tty = open ("/dev/tty", O_RDONLY);
  786.   if (tty != -1)
  787.     {
  788. #ifdef NEW_TTY_DRIVER
  789.       ioctl (tty, TIOCGETP, &shell_tty_info);
  790.       ioctl (tty, TIOCGETC, &shell_tchars);
  791.       ioctl (tty, TIOCGLTC, &shell_ltchars);
  792. #else
  793.       ioctl (tty, TCGETA, &shell_tty_info);
  794. #endif /* NEW_TTY_DRIVER */
  795.       close (tty);
  796.     }
  797. }
  798.  
  799. /* Make the current tty use the state in shell_tty_info. */
  800. set_tty_state ()
  801. {
  802.   int tty = open ("/dev/tty", O_RDONLY);
  803.   if (tty != -1)
  804.     {
  805. #ifdef NEW_TTY_DRIVER
  806.       ioctl (tty, TIOCSETN, &shell_tty_info);
  807.       ioctl (tty, TIOCSETC, &shell_tchars);
  808.       ioctl (tty, TIOCSLTC, &shell_ltchars);
  809. #else
  810.       ioctl (tty, TCSETAW, &shell_tty_info);
  811. #endif /* NEW_TTY_DRIVER */
  812.       close (tty);
  813.     }
  814. }
  815.  
  816. /* Given an index into the jobs array JOB, return the pid of the last process
  817.    in that job's pipeline.  This is the one whose exit status counts. */
  818. int
  819. lastproc (job)
  820.      int job;
  821. {
  822.   int oldmask = sigblock (sigmask (SIGCHLD));
  823.   register PROCESS *p;
  824.  
  825.   p = jobs[job]->pipe;
  826.   while (p->next != jobs[job]->pipe)
  827.     p = p->next;
  828.  
  829.   sigsetmask (oldmask);
  830.   return (p->pid);
  831. }
  832.  
  833. /* Wait for a particular child of the shell to finish executing.
  834.    This low-level function prints an error message if PID is not
  835.    a child of this shell.  It returns -1 if it fails, or 0 if not. */
  836. int
  837. wait_for_single_pid (pid)
  838.      int pid;
  839. {
  840.   register PROCESS *child;
  841.  
  842.   child = find_pipeline (pid);
  843.  
  844.   if (!child)
  845.     {
  846.       report_error ("wait: pid %d is not a child of this shell", pid);
  847.       return (-1);
  848.     }
  849.  
  850.   return (wait_for (pid));
  851. }
  852.  
  853. /* Wait for all of the backgrounds of this shell to finish. */
  854. wait_for_background_pids ()
  855. {
  856.   while (1)
  857.     {
  858.       register int i, count = 0;
  859.       int oldmask = sigblock (sigmask (SIGCHLD));
  860.  
  861.       for (i = 0; i < job_slots; i++)
  862.     if (jobs[i] && (JOBSTATE (i) == JRUNNING) && !(jobs[i]->foreground))
  863.       {
  864.         count++;
  865.         break;
  866.       }
  867.  
  868.       if (!count)
  869.     {
  870.       sigsetmask (oldmask);
  871.       break;
  872.     }
  873.  
  874.       for (i = 0; i < job_slots; i++)
  875.     if (jobs[i] && (JOBSTATE (i) == JRUNNING) && !jobs[i]->foreground)
  876.       {
  877.         int pid = jobs[i]->pgrp;
  878.         sigsetmask (oldmask);
  879.         QUIT;
  880.         wait_for_single_pid (pid);
  881.         break;
  882.       }
  883.     }
  884. }
  885.  
  886. /* Wait for pid (one of our children) to terminate. */
  887. int
  888. wait_for (pid)
  889.      int pid;
  890. {
  891.   int oldmask, job, termination_state;
  892.   register PROCESS *child;
  893.   extern char *sys_siglist[];
  894.   extern int interactive;
  895.  
  896.   oldmask = sigblock (sigmask (SIGCHLD));
  897.  
  898.   /* If we say wait_for (), then we have a record of this child somewhere.
  899.      If this child and all of its peers are not running, then don't
  900.      sigpause (), since there is no need to. */
  901.  wait_loop:
  902.  
  903.   /* If the shell is running interactively, then let the user C-c out. */
  904.   if (interactive)
  905.     QUIT;
  906.  
  907.   child = find_pipeline (pid);
  908.  
  909.   if (!child)
  910.     {
  911.       give_terminal_to (shell_pgrp);
  912.       programming_error ("wait_for: No record of pid %d", pid);
  913.     }
  914.  
  915.   /* If this child is part of a job, then we are really waiting for the
  916.      job to finish.  Otherwise, we are waiting for the child to finish. */
  917.  
  918.   job = find_job (pid);
  919.  
  920.   if (job != NO_JOB)
  921.     {
  922.       register int job_state = 0, any_stopped = 0;
  923.       register PROCESS *p = jobs[job]->pipe;
  924.  
  925.       do
  926.     {
  927.       job_state |= p->running;
  928.       if (!p->running)
  929.         any_stopped |= WIFSTOPPED (p->status);
  930.       p = p->next;
  931.     }
  932.       while (p != jobs[job]->pipe);
  933.  
  934.       if (job_state == 0)
  935.     {
  936.       if (any_stopped)
  937.         jobs[job]->state = JSTOPPED;
  938.       else
  939.         jobs[job]->state = JDEAD;
  940.     }
  941.     }
  942.  
  943.   if (child->running ||
  944.       ((job != NO_JOB) && (JOBSTATE (job) == JRUNNING)))
  945.     {
  946.       sigpause ((long)0);
  947.       goto wait_loop;
  948.     }
  949.  
  950.   /* The exit state of the command is either the termination state of the
  951.      child, or the termination state of the job.  If a job, the status
  952.      of the last child in the pipeline is the significant one. */
  953.  
  954.   if (job != NO_JOB)
  955.     {
  956.       register PROCESS *p = jobs[job]->pipe;
  957.  
  958.       while (p->next != jobs[job]->pipe)
  959.     p = p->next;
  960.       termination_state = p->status.w_retcode;
  961.     }
  962.   else
  963.     termination_state = child->status.w_retcode;
  964.  
  965.   if (job == NO_JOB || jobs[job]->job_control)
  966.     give_terminal_to (shell_pgrp);
  967.  
  968.   /* If the command did not exit cleanly, or the job is just
  969.      being stopped, then reset the tty state back to what it
  970.      was before this command. */
  971.   if ((child->status.w_termsig != 0 || (WIFSTOPPED (child->status))))
  972.     set_tty_state ();
  973.   else
  974.     get_tty_state ();
  975.  
  976.   if (job != NO_JOB)
  977.     notify_and_cleanup ();
  978.  
  979.  wait_exit:
  980.   sigsetmask (oldmask);
  981.   return (termination_state);
  982. }
  983.  
  984. /* Wait for the last process in the pipeline for JOB. */
  985. int
  986. wait_for_job (job)
  987.      int job;
  988. {
  989.   int pid = lastproc (job);
  990.   return (wait_for (pid));
  991. }
  992.  
  993. /* Print info about dead jobs, and then delete them from the list
  994.    of known jobs. */
  995. notify_and_cleanup ()
  996. {
  997.   notify_of_job_status ();
  998.   cleanup_dead_jobs ();
  999. }
  1000.  
  1001. /* Return the next closest (chronologically) job to JOB which is in
  1002.    STATE.  STATE can be JSTOPPED, JRUNNING.  NO_JOB is returned if
  1003.    there is no next recent job. */
  1004. static int
  1005. most_recent_job_in_state (job, state)
  1006.      int job;
  1007.      JOB_STATE state;
  1008. {
  1009.   register int i;
  1010.   int oldmask = sigblock (sigmask (SIGCHLD));
  1011.  
  1012.   for (i = job - 1; i >= 0; i--)
  1013.     {
  1014.       if (jobs[i])
  1015.     {
  1016.       if (JOBSTATE (i) == state)
  1017.         {
  1018.           /* Found it! */
  1019.           sigsetmask (oldmask);
  1020.           return (i);
  1021.         }
  1022.     }
  1023.     }
  1024.   sigsetmask (oldmask);
  1025.   return (NO_JOB);
  1026. }
  1027.  
  1028. /* Return the newest *stopped* job older than JOB, or NO_JOB if not
  1029.    found. */
  1030. static int
  1031. last_stopped_job (job)
  1032.      int job;
  1033. {
  1034.   return (most_recent_job_in_state (job, JSTOPPED));
  1035. }
  1036.  
  1037. /* Return the newest *running* job older than JOB, or NO_JOB if not
  1038.    found. */
  1039. static int
  1040. last_running_job (job)
  1041.      int job;
  1042. {
  1043.   return (most_recent_job_in_state (job, JRUNNING));
  1044. }
  1045.  
  1046. /* Make JOB be the current job, and make previous be useful. */
  1047. set_current_job (job)
  1048.      int job;
  1049. {
  1050.   int candidate = NO_JOB;
  1051.  
  1052.   if (current_job != job)
  1053.     {
  1054.       previous_job = current_job;
  1055.       current_job = job;
  1056.     }
  1057.  
  1058.   /* First choice for previous_job is the old current_job. */
  1059.   if (previous_job != current_job &&
  1060.       previous_job != NO_JOB &&
  1061.       JOBSTATE (previous_job) == JSTOPPED)
  1062.     return;
  1063.  
  1064.   /* Second choice:  Newest stopped job that is older than
  1065.      the current job. */
  1066.   if (JOBSTATE (current_job) == JSTOPPED)
  1067.     {
  1068.       candidate = last_stopped_job (current_job);
  1069.  
  1070.       if (candidate != NO_JOB)
  1071.     {
  1072.       previous_job = candidate;
  1073.       return;
  1074.     }
  1075.     }
  1076.  
  1077.   if (JOBSTATE (current_job) == JRUNNING)
  1078.     candidate = last_running_job (current_job);
  1079.   else
  1080.     candidate = last_running_job (job_slots);
  1081.  
  1082.   if (candidate != NO_JOB)
  1083.     {
  1084.       previous_job = candidate;
  1085.       return;
  1086.     }
  1087.  
  1088.   /* There is only a single job, and it is both `+' and `-'. */
  1089.   previous_job = current_job;
  1090. }
  1091.  
  1092. /* Make current_job be something useful, if it isn't already. */
  1093. reset_current ()
  1094. {
  1095.   int candidate = NO_JOB;
  1096.  
  1097.   if (current_job != NO_JOB &&
  1098.       job_slots && jobs[current_job] &&
  1099.       JOBSTATE (current_job) == JSTOPPED)
  1100.     {
  1101.       candidate = current_job;
  1102.     }
  1103.   else
  1104.     {
  1105.       /* First choice:  the previous job! */
  1106.       if (previous_job != NO_JOB && jobs[previous_job] &&
  1107.       JOBSTATE (previous_job) == JSTOPPED)
  1108.     candidate = previous_job;
  1109.  
  1110.       /* Second choice: the most recently stopped job. */
  1111.       candidate = last_stopped_job (job_slots);
  1112.  
  1113.       if (candidate == NO_JOB)
  1114.     {
  1115.       /* Third choice: the newest running job. */
  1116.       candidate = last_running_job (job_slots);
  1117.     }
  1118.     }
  1119.  
  1120.   /* If we found a job to use, then use it.  Otherwise, there
  1121.      are no jobs period. */
  1122.   if (candidate != NO_JOB)
  1123.     set_current_job (candidate);
  1124.   else
  1125.     current_job = previous_job = NO_JOB;
  1126. }
  1127.  
  1128. /* Start a job.  FOREGROUND if non-zero says to do that.  Otherwise,
  1129.    start the job in the background.  JOB is a zero-based index into
  1130.    JOBS.  Returns zero if it is unable to start a job. */
  1131. int
  1132. start_job (job, foreground)
  1133.      int job, foreground;
  1134. {
  1135.   int oldmask = sigblock (sigmask (SIGCHLD));
  1136.   int already_running = (JOBSTATE (job) == JRUNNING);
  1137.   register PROCESS *p;
  1138.  
  1139.   if (!foreground && already_running)
  1140.     {
  1141.       extern char *this_command_name;
  1142.  
  1143.       report_error ("%s: bg background job?", this_command_name);
  1144.       return (0);
  1145.     }
  1146.  
  1147.   /* You don't know about the state of this job.  Do you? */
  1148.   jobs[job]->notified = 0;
  1149.  
  1150.   if (foreground)
  1151.     {
  1152.       set_current_job (job);
  1153.       jobs[job]->foreground = 1;
  1154.     }
  1155.  
  1156.   /* Tell the outside world what we're doing. */
  1157.   p = jobs[job]->pipe;
  1158.  
  1159.   do
  1160.     {
  1161.       fprintf (stderr, "%s%s",
  1162.            p->command, p->next != jobs[job]->pipe? " | " : "");
  1163.       p = p->next;
  1164.     }
  1165.   while (p != jobs[job]->pipe);
  1166.  
  1167.   if (!foreground)
  1168.     fprintf (stderr, " &");
  1169.       
  1170.   if (strcmp (get_string_value ("PWD"), jobs[job]->wd) != 0)
  1171.     fprintf (stderr, "  (wd: %s)", polite_directory_format (jobs[job]->wd));
  1172.  
  1173.   fprintf (stderr, "\n");
  1174.   
  1175.   /* Run the job. */
  1176.  
  1177.   if (!already_running)
  1178.     {
  1179.       /* Each member of the pipeline is now running. */
  1180.       p = jobs[job]->pipe;
  1181.  
  1182.       do
  1183.     {
  1184.       if (WIFSTOPPED (p->status))
  1185.         p->running = 1;
  1186.       p = p->next;
  1187.     }
  1188.       while (p != jobs[job]->pipe);
  1189.  
  1190.     /* This means that the job is running. */
  1191.     JOBSTATE (job) = JRUNNING;
  1192.   }
  1193.  
  1194.   /* Give the terminal to this job. */
  1195.   if (foreground)
  1196.     {
  1197.       if (jobs[job]->job_control)
  1198.     give_terminal_to (jobs[job]->pgrp);
  1199.     }
  1200.   else
  1201.     jobs[job]->foreground = 0;
  1202.  
  1203.   /* If the job is already running, then don't bother jump-starting it. */
  1204.   if (!already_running)
  1205.     {
  1206.       jobs[job]->notified = 1;
  1207.       killpg (jobs[job]->pgrp, SIGCONT);
  1208.     }
  1209.  
  1210.   sigsetmask (oldmask);
  1211.  
  1212.   if (foreground)
  1213.     {
  1214.       int pid = lastproc (job);
  1215.  
  1216.       return (!wait_for (pid));
  1217.     }
  1218.   else
  1219.     reset_current ();
  1220.  
  1221.   return (1);
  1222. }
  1223.  
  1224. /* Give PID SIGNAL.  This determines what job the pid belongs to (if any).
  1225.    If PID does belong to a job, and the job is stopped, then CONTinue the
  1226.    job after giving it SIGNAL.  Returns -1 on failure.  If GROUP is non-null,
  1227.    then kill the process group associated with PID. */
  1228. int
  1229. kill_pid (pid, signal, group)
  1230.      int pid, signal, group;
  1231. {
  1232.   int old_mask = sigblock (sigmask (SIGCHLD));
  1233.   register PROCESS *p = find_pipeline (pid);
  1234.   int job = find_job (pid);
  1235.   int result = EXECUTION_SUCCESS;
  1236.  
  1237.   if (group)
  1238.     {
  1239.       if (job != NO_JOB)
  1240.     {
  1241.       jobs[job]->notified = 0;
  1242.  
  1243.       /* Kill process in backquotes or one started with job control? */
  1244.       if (jobs[job]->pgrp == shell_pgrp)
  1245.         {
  1246.           p = jobs[job]->pipe;
  1247.  
  1248.           do
  1249.         {
  1250.           if (!p->running && (signal == SIGTERM || signal == SIGHUP))
  1251.             kill (pid, SIGCONT);
  1252.           kill (pid, signal);
  1253.           p = p->next;
  1254.         } while (p != jobs[job]->pipe);
  1255.         }
  1256.       else
  1257.         {
  1258.           if (p && (JOBSTATE (job) == JSTOPPED) &&
  1259.           (signal == SIGTERM || signal == SIGHUP))
  1260.         killpg (jobs[job]->pgrp, SIGCONT);
  1261.           result = killpg (jobs[job]->pgrp, signal);
  1262.         }
  1263.     }
  1264.       else
  1265.     {
  1266.       result = killpg (pid, signal);
  1267.     }
  1268.     }
  1269.   else
  1270.     {
  1271.       result = kill (pid, signal);
  1272.     }
  1273.   sigsetmask (old_mask);
  1274.   return (result);
  1275. }
  1276.  
  1277. /* Flush_child () flushes at least one of the children that we are waiting for.
  1278.    It gets run when we have gotten a SIGCHLD signal, and stops when there
  1279.    aren't any children terminating any more. */
  1280. sighandler
  1281. flush_child (sig, code)
  1282.      int sig, code;
  1283. {
  1284.   union wait status;
  1285. #ifndef hpux
  1286.   struct rusage rusage;
  1287. #endif
  1288.   PROCESS *child;
  1289.   int pid, call_set_current = 0, last_stopped_job = NO_JOB;
  1290.  
  1291.   do
  1292.     {
  1293. #ifdef hpux
  1294.       pid = wait3 (&status, (WNOHANG | WUNTRACED), (int *)0);
  1295. #else
  1296.       pid = wait3 (&status, (WNOHANG | WUNTRACED), &rusage);
  1297. #endif /* hpux */
  1298.  
  1299.       if (pid > 0)
  1300.     {
  1301. #ifdef hpux
  1302.       /* Reinstall the signal handler.  That's what HPUX makes us do. */
  1303.       signal (SIGCHLD, flush_child);
  1304. #endif
  1305.  
  1306. #ifdef NEVER /* Claim is made that times_builtin can handle it. */
  1307.       /* Keep track of total time used. */
  1308.       if (! WIFSTOPPED (status))
  1309.         add_times (&rusage);
  1310. #endif /* NEVER */
  1311.  
  1312.       /* Locate our PROCESS for this pid. */
  1313.       child = find_pipeline (pid);
  1314.  
  1315.       /* It is not an error to have a child terminate that we did
  1316.          not have a record of.  This child could have been part of
  1317.          a pipeline in backquote substitution. */
  1318.       if (child)
  1319.         {
  1320.           int job = find_job (pid);
  1321.  
  1322.           while (child->pid != pid)
  1323.         child = child->next;
  1324.  
  1325.           /* Remember status, and fact that process is not running. */
  1326.           child->status = status;
  1327.           child->running = 0;
  1328.  
  1329.           if (job != NO_JOB)
  1330.         {
  1331.           int job_state = 0;
  1332.           int any_stopped = 0;
  1333.  
  1334.           child = jobs[job]->pipe;
  1335.           jobs[job]->notified = 0;
  1336.           
  1337.           /* If all children are not running, but any of them is
  1338.              stopped, then the job is stopped, not dead. */
  1339.           do
  1340.             {
  1341.               job_state |= child->running;
  1342.               if (!child->running)
  1343.             any_stopped |= (WIFSTOPPED (child->status));
  1344.               child = child->next;
  1345.             }
  1346.           while (child != jobs[job]->pipe);
  1347.  
  1348.           if (job_state == 0)
  1349.             {
  1350.               if (any_stopped)
  1351.             {
  1352.               jobs[job]->state = JSTOPPED;
  1353.               jobs[job]->foreground = 0;
  1354.               call_set_current++;
  1355.               last_stopped_job = job;
  1356.             }
  1357.               else
  1358.             {
  1359.               jobs[job]->state = JDEAD;
  1360.  
  1361.               if (job == last_stopped_job)
  1362.                 last_stopped_job = NO_JOB;
  1363.  
  1364.               /* If this job was not started with job control,
  1365.                  then the shell has already seen the SIGINT, since
  1366.                  the process groups are the same.  In that case,
  1367.                  don't send the SIGINT to the shell; it will
  1368.                  surprise people to have a stray interrupt
  1369.                  arriving some time after they killed the job. */
  1370.  
  1371.               if (jobs[job]->foreground &&
  1372.                   jobs[job]->job_control &&
  1373.                   jobs[job]->pipe->status.w_termsig == SIGINT)
  1374.                 kill (getpid (), SIGINT);
  1375.             }
  1376.             }
  1377.         }
  1378.         }
  1379.     }
  1380.     }
  1381.   while (pid > 0);
  1382.  
  1383.   /* If a job was running and became stopped, then set the current
  1384.      job.  Otherwise, don't change a thing. */
  1385.   if (call_set_current)
  1386.     if (last_stopped_job != NO_JOB)
  1387.       set_current_job (last_stopped_job);
  1388.     else
  1389.       reset_current ();
  1390.  
  1391.   /* We have successfully recorded the useful information about this process
  1392.      that has just changed state.  If we notify asynchronously, and the job
  1393.      that this process belongs to is no longer running, then notify the user
  1394.      of that fact now. */
  1395.   if (asynchronous_notification)
  1396.     notify_of_job_status ();
  1397. }
  1398.  
  1399. /* Function to call when you want to notify people of changes
  1400.    in job status.  This prints out all jobs which are pending
  1401.    notification to stderr, and marks those printed as already
  1402.    notified, thus making them candidates for cleanup. */
  1403. notify_of_job_status ()
  1404. {
  1405.   extern char *sys_siglist[];
  1406.   register int job, termsig;
  1407.   char *dir = (char *)get_string_value ("PWD");
  1408.   int oldmask = sigblock (sigmask (SIGCHLD) | sigmask (SIGTTOU));
  1409.  
  1410.   for (job = 0; job < job_slots; job++)
  1411.     {
  1412.       if (jobs[job] && jobs[job]->notified == 0)
  1413.     {
  1414.       termsig = jobs[job]->pipe->status.w_termsig;
  1415.  
  1416.       switch (JOBSTATE (job))
  1417.         {
  1418.           /* Print info on jobs that are running in the background,
  1419.          and on foreground jobs that were killed by anything
  1420.          except SIGINT. */
  1421.  
  1422.         case JDEAD:
  1423.  
  1424.           if (jobs[job]->foreground)
  1425.         {
  1426.           if (termsig && termsig != WSTOPPED && termsig != SIGINT)
  1427.             {
  1428.               fprintf (stderr, "%s", sys_siglist[termsig]);
  1429.  
  1430.               if (jobs[job]->pipe->status.w_coredump)
  1431.             fprintf (stderr, " (core dumped)");
  1432.  
  1433.               fprintf (stderr, "\n");
  1434.             }
  1435.         }
  1436.           else
  1437.         {
  1438.           pretty_print_job (job, 0, stderr);
  1439.           if (dir && strcmp (dir, jobs[job]->wd) != 0)
  1440.             fprintf (stderr,
  1441.                  "(wd now: %s)\n", polite_directory_format (dir));
  1442.         }
  1443.           jobs[job]->notified = 1;
  1444.           break;
  1445.  
  1446.         case JSTOPPED:
  1447.           fprintf (stderr, "\n");
  1448.           pretty_print_job (job, 0, stderr);
  1449.           if (dir && (strcmp (dir, jobs[job]->wd) != 0))
  1450.         fprintf (stderr,
  1451.              "(wd now: %s)\n", polite_directory_format (dir));
  1452.           jobs[job]->notified = 1;
  1453.           break;
  1454.  
  1455.         case JRUNNING:
  1456.         case JMIXED:
  1457.           break;
  1458.  
  1459.         default:
  1460.           programming_error ("notify_of_job_status");
  1461.         }
  1462.     }
  1463.     }
  1464.   sigsetmask (oldmask);
  1465. }
  1466.  
  1467. #ifndef hpux
  1468. add_times (rused)
  1469.      struct rusage *rused;
  1470. {
  1471.   total_systime.tv_usec += rused->ru_stime.tv_usec;
  1472.   total_systime.tv_sec += rused->ru_stime.tv_sec;
  1473.  
  1474.   if (total_systime.tv_usec > 1000000)
  1475.     {
  1476.       total_systime.tv_sec++;
  1477.       total_systime.tv_usec -= 1000000;
  1478.     }
  1479.  
  1480.   total_usertime.tv_usec += rused->ru_utime.tv_usec;
  1481.   total_usertime.tv_sec += rused->ru_utime.tv_sec;
  1482.  
  1483.   if (total_usertime.tv_usec > 1000000)
  1484.     {
  1485.       total_usertime.tv_sec++;
  1486.       total_usertime.tv_usec -= 1000000;
  1487.     }
  1488.  
  1489.   if (total_systime.tv_sec)
  1490.     {
  1491.       system_minutes_used = (total_systime.tv_sec / 60);
  1492.       system_seconds_used = (total_systime.tv_sec % 60);
  1493.     }
  1494.  
  1495.   if (total_usertime.tv_sec)
  1496.     {
  1497.       user_minutes_used = (total_usertime.tv_sec / 60);
  1498.       user_seconds_used = (total_usertime.tv_sec % 60);
  1499.     }
  1500. }
  1501. #endif /* hpux */
  1502.  
  1503. #ifdef hpux
  1504. getdtablesize ()
  1505. {
  1506.   return (NOFILE);
  1507. }
  1508. #endif /* hpux */
  1509.  
  1510. /* Initialize the job control mechanism, and set up the tty stuff. */
  1511. initialize_jobs ()
  1512. {
  1513.   extern int interactive;
  1514.  
  1515.   shell_pgrp = getpgrp (0);
  1516.  
  1517.   /* We can only have job control if we are interactive?
  1518.      I guess that makes sense. */
  1519.  
  1520.   if (!job_control || !interactive)
  1521.     {
  1522.       job_control = 0;
  1523.     }
  1524.   else
  1525.     {
  1526.       char *err_string = "get";
  1527.  
  1528.       /* Make sure that we are using the new line discipline. */
  1529.       int ldisc;
  1530.  
  1531.       /* Get our controlling terminal.  If job_control is set, or
  1532.      interactive is set, then this is an interactive shell no
  1533.      matter what opening /dev/tty returns.  (It sometimes says
  1534.      the wrong thing.) */
  1535.       shell_tty = open ("/dev/tty", O_RDWR, 0666);
  1536.       if (shell_tty < 0)
  1537.     shell_tty = dup (fileno (stdin));
  1538.  
  1539.       /* Find the highest unused file descriptor we can. */
  1540.       {
  1541.     int ignore, nds = getdtablesize ();
  1542.     
  1543.     while (--nds > 3)
  1544.       {
  1545.         if (fcntl (nds, F_GETFD, &ignore) == -1)
  1546.           break;
  1547.       }
  1548.  
  1549.     if (shell_tty != nds && (dup2 (shell_tty, nds) != -1))
  1550.       {
  1551.         if (shell_tty != fileno (stdin))
  1552.           close (shell_tty);
  1553.         shell_tty = nds;
  1554.       }
  1555.       }
  1556.  
  1557.       while ((terminal_pgrp = tcgetpgrp (shell_tty)) != -1)
  1558.     {
  1559.       if (shell_pgrp != terminal_pgrp)
  1560.         {
  1561.           SigHandler *old_ttin = (SigHandler *)signal (SIGTTIN, SIG_DFL);
  1562.           kill (0, SIGTTIN);
  1563.           signal (SIGTTIN, old_ttin);
  1564.           continue;
  1565.         }
  1566.       break;
  1567.     }
  1568.  
  1569. #ifdef NEW_TTY_DRIVER
  1570.       if (ioctl (shell_tty, TIOCGETD, &ldisc) < 0)
  1571.     goto bad_ioctl;
  1572.  
  1573.       if (ldisc != NTTYDISC)
  1574.     {
  1575.       ldisc = NTTYDISC;
  1576.       err_string = "set";
  1577.       if (ioctl (shell_tty, TIOCSETD, &ldisc) < 0)
  1578.         {
  1579.         bad_ioctl:
  1580.           fprintf (stderr, "initialize_jobs: %s line disc: ", err_string);
  1581.           job_control = 0;
  1582.           file_error ("jobs.c");
  1583.         }
  1584.     }
  1585. #endif /* NEW_TTY_DRIVER */
  1586.  
  1587.       original_pgrp = shell_pgrp;
  1588.       shell_pgrp = getpid ();
  1589.       give_terminal_to (shell_pgrp);
  1590.       setpgid (0, shell_pgrp);
  1591.  
  1592. #ifndef FD_CLOEXEC
  1593. #define FD_CLOEXEC 1
  1594. #endif
  1595.  
  1596.       if (shell_tty != fileno (stdin))
  1597.     fcntl (shell_tty, F_SETFD, FD_CLOEXEC);
  1598.  
  1599.       job_control = 1;
  1600.     }
  1601.  
  1602.   signal (SIGCHLD, flush_child);
  1603.   /* We don't call set_job_control here, because change_flag_char ()
  1604.      does that for us. */
  1605.   /* set_job_control (job_control); */
  1606.   change_flag_char ('m', job_control ? '-' : '+');
  1607.  
  1608.   get_tty_state ();
  1609. }
  1610.  
  1611. /* Allow or disallow job control to take place. */
  1612. set_job_control (arg)
  1613.      int arg;
  1614. {
  1615.   job_control = arg;
  1616. }
  1617.  
  1618. static SigHandler *old_tstp, *old_ttou, *old_ttin;
  1619. static SigHandler *old_cont = (SigHandler *)SIG_DFL;
  1620.  
  1621. /* Setup this shell to handle C-C, etc. */
  1622. initialize_job_signals ()
  1623. {
  1624.   extern int login_shell;
  1625.   sighandler sigint_sighandler ();
  1626.  
  1627.   signal (SIGINT, sigint_sighandler);
  1628.   signal (SIGQUIT, SIG_IGN);
  1629.  
  1630.   if (login_shell)
  1631.     {
  1632.       signal (SIGTSTP, SIG_IGN);
  1633.       signal (SIGTTOU, SIG_IGN);
  1634.       signal (SIGTTIN, SIG_IGN);
  1635.     }
  1636.   else
  1637.     {
  1638.       static sighandler stop_signal_handler ();
  1639.  
  1640.       old_tstp = (SigHandler *)signal (SIGTSTP, stop_signal_handler);
  1641.       old_ttou = (SigHandler *)signal (SIGTTOU, stop_signal_handler);
  1642.       old_ttin = (SigHandler *)signal (SIGTTIN, stop_signal_handler);
  1643.     }
  1644. }
  1645.  
  1646. /* Here we handle CONT signals. */
  1647. static sighandler
  1648. cont_signal_handler (sig, code)
  1649.      int sig, code;
  1650. {
  1651.   initialize_job_signals ();
  1652.   signal (SIGCONT, old_cont);
  1653.   kill (getpid (), SIGCONT);
  1654. }
  1655.  
  1656. /* Here we handle stop signals while we are running not as a login shell. */
  1657. static sighandler
  1658. stop_signal_handler (sig, code)
  1659.      int sig, code;
  1660. {
  1661.   signal (SIGTSTP, old_tstp);
  1662.   signal (SIGTTOU, old_ttou);
  1663.   signal (SIGTTIN, old_ttin);
  1664.  
  1665.   old_cont = (SigHandler *)signal (SIGCONT, cont_signal_handler);
  1666.  
  1667.   give_terminal_to (shell_pgrp);
  1668.  
  1669.   kill (getpid (), sig);
  1670. }
  1671.  
  1672. /* Give the terminal to PGRP.  */
  1673. give_terminal_to (pgrp)
  1674.      int pgrp;
  1675. {
  1676.   int oldmask;
  1677.  
  1678.   if (job_control)
  1679.     {
  1680.       oldmask = sigblock (sigmask (SIGTTOU) |
  1681.               sigmask (SIGTTIN) |
  1682.               sigmask (SIGTSTP) |
  1683.               sigmask (SIGCHLD));
  1684.  
  1685.       terminal_pgrp = pgrp;
  1686.       tcsetpgrp (shell_tty, terminal_pgrp);
  1687.       sigsetmask (oldmask);
  1688.     }
  1689. }
  1690.  
  1691. /* Clear out any jobs in the job array.  This is intended to be used by
  1692.    children of the shell, who should not have any job structures as baggage
  1693.    when they start executing (forking subshells for parenthesized execution
  1694.    and functions with pipes are the two that spring to mind). */
  1695.  
  1696. delete_all_jobs ()
  1697. {
  1698.   if (job_slots)
  1699.     {
  1700.       register int i;
  1701.  
  1702.       for (i = 0; i < job_slots; i++)
  1703.     if (jobs[i] != (JOB *) NULL)
  1704.       delete_job (i);
  1705.  
  1706.       free ((char *)jobs);
  1707.       job_slots = 0;
  1708.     }
  1709. }
  1710.  
  1711. /* Turn off all traces of job control.  This is run by children of the shell
  1712.    which are going to do shellsy things, like wait (), etc. */
  1713. without_job_control ()
  1714. {
  1715.   stop_making_children ();
  1716.   start_pipeline ();
  1717.   delete_all_jobs ();
  1718.   set_job_control (0);
  1719. }
  1720. #endif  /* JOB_CONTROL */
  1721.  
  1722.